'use client'

import { useState } from 'react'
import { Sheet } from '@/types/sheet'
import { AppLayout } from '@/components/layout/AppLayout'
import { HomePage } from '@/components/pages/HomePage'
import { SheetPage } from '@/components/pages/SheetPage'
import { CreateSheetModal } from '@/components/modals/CreateSheetModal'
import { AuthModal } from '@/components/auth/AuthModal'
import { useAuth } from '@/contexts/AuthContext'
import { FileSpreadsheet } from 'lucide-react'

export default function Home() {
  const { user, loading: authLoading } = useAuth()
  const [currentSheet, setCurrentSheet] = useState<Sheet | null>(null)
  const [showCreateModal, setShowCreateModal] = useState(false)
  const [showAuthModal, setShowAuthModal] = useState(false)

  // 处理表格选择
  const handleSheetSelect = (sheet: Sheet) => {
    setCurrentSheet(sheet)
  }

  // 处理创建表格成功
  const handleCreateSuccess = (sheet: Sheet) => {
    setCurrentSheet(sheet)
  }

  // 处理返回首页
  const handleBack = () => {
    setCurrentSheet(null)
  }

  // 如果正在加载认证状态，直接返回null
  if (authLoading) {
    return null
  }

  // 如果用户未登录，显示登录页面
  if (!user) {
    return (
      <div className="min-h-screen bg-gray-50 dark:bg-gray-900 flex items-center justify-center">
        <div className="text-center">
          <FileSpreadsheet size={64} className="mx-auto text-gray-400 mb-4" />
          <h1 className="text-3xl font-bold text-gray-900 dark:text-white mb-4">
            协作表格
          </h1>
          <p className="text-gray-600 dark:text-gray-400 mb-8">
            登录或注册开始使用协作表格功能
          </p>
          <button
            onClick={() => setShowAuthModal(true)}
            className="px-6 py-3 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors font-medium"
          >
            登录 / 注册
          </button>
        </div>
        
        <AuthModal 
          isOpen={showAuthModal} 
          onClose={() => setShowAuthModal(false)}
          initialMode="login"
        />
      </div>
    )
  }

  return (
    <AppLayout
      currentSheet={currentSheet}
      onSheetSelect={handleSheetSelect}
      onSheetCreated={handleCreateSuccess}
    >
      {currentSheet ? (
        <SheetPage
          sheetId={currentSheet.id}
          onBack={handleBack}
        />
      ) : (
        <HomePage onCreateSheet={() => setShowCreateModal(true)} />
      )}

      <CreateSheetModal
        isOpen={showCreateModal}
        onClose={() => setShowCreateModal(false)}
        onSuccess={handleCreateSuccess}
      />
    </AppLayout>
  )
}